package com.beagle.njddapp.ui.activity.owner;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.beagle.njddapp.R;
import com.beagle.njddapp.base.BaseMvpActivity;
import com.beagle.njddapp.bean.owner.NongJiBean;
import com.beagle.njddapp.bean.UploadBean;
import com.beagle.njddapp.bean.ZdBean;
import com.beagle.njddapp.event.AddDeviceEvent;
import com.beagle.njddapp.ui.presenter.DeviceAddPresenter;
import com.beagle.njddapp.ui.view.DeviceAddView;
import com.beagle.njddapp.utils.GlideEngine;
import com.beagle.njddapp.utils.StatusBarUtil;
import com.beagle.njddapp.utils.Utils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import butterknife.BindView;
import butterknife.OnClick;

import static com.beagle.njddapp.ui.activity.BasicUserInfoActivity.CHOOSE_IMG_BACK;
import static com.beagle.njddapp.ui.activity.BasicUserInfoActivity.CHOOSE_IMG_FRONT;

/**
 * @author hxx
 * @date 2021-03-02 22:31
 * 添加nongji
 */
public class DeviceAddStepTwoActivity extends BaseMvpActivity<DeviceAddView, DeviceAddPresenter> implements DeviceAddView, View.OnClickListener {


    @BindView(R.id.commom_title_tv)
    TextView tvTitle;
    @BindView(R.id.common_container)
    RelativeLayout container;
    @BindView(R.id.common_tv_right)
    TextView tvRight;
    @BindView(R.id.ed_device_gauche)
    EditText edGuache;
    @BindView(R.id.ed_device_jxs)
    EditText edJxs;
    @BindView(R.id.ed_device_jsx_place)
    EditText edJxsPlace;
    @BindView(R.id.ed_device_youliang)
    EditText edYouLiang;
    @BindView(R.id.ed_device_zd_number)
    EditText edBianhao;
    @BindView(R.id.ed_device_size)
    EditText edSize;
    @BindView(R.id.ed_device_zhiliang)
    EditText edzhiliang;
    @BindView(R.id.ed_device_gonglv)
    EditText edGonglv;
    @BindView(R.id.ll_device_iv)
    LinearLayout lliv1;
    @BindView(R.id.iv1)
    ImageView ivFront;
    @BindView(R.id.iv2)
    ImageView ivback;
    @BindView(R.id.ed_card_number)
    EditText edCardNumber;
    @BindView(R.id.prograssBar)
    ProgressBar progressBar;
    private NongJiBean nongJiBean;
    private List<View> imgViews;
    private List<String> paths;
    private static  final int CHOOSE_IMG=1004;
    private AtomicInteger size;
    private boolean isNoNj;

    @Override
    public int getLayoutId() {
        return R.layout.activity_device_add_step_two;
    }


    @Override
    public void init() {
        isNoNj=getIntent().getBooleanExtra("isNoNj",false);
        StatusBarUtil.immersive(this, Color.WHITE);
        StatusBarUtil.darkMode(this);
        tvTitle.setText("添加农机设备");
        nongJiBean= (NongJiBean) getIntent().getSerializableExtra("data");
        paths=new ArrayList<>();
        imgViews=new ArrayList<>();
        size=new AtomicInteger(0);
        addFirstIv();
    }

    private void addFirstIv() {

        View view=LayoutInflater.from(this).inflate(R.layout.item_add_img,null);
        ImageView ivAdd=view.findViewById(R.id.iv_add);
        ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Matisse.from(DeviceAddStepTwoActivity.this)
                        .choose(MimeType.ofImage())
                        .capture(true)
                        .countable(true)
                        .maxSelectable(1)
                        .thumbnailScale(0.85f)
                        .captureStrategy(new CaptureStrategy(true, "com.beagle.njddapp"))
                        .imageEngine(GlideEngine.getInstance())
                        .showPreview(false) // Default is `true`
                        .forResult(CHOOSE_IMG);
            }
        });
        imgViews.add(view);
        lliv1.addView(view);
    }

    @Override
    public DeviceAddView getMvpView() {
        return this;
    }

    @Override
    public DeviceAddPresenter createPresenter() {
        return new DeviceAddPresenter();
    }

    @Override
    public void onError(String message) {
        ToastUtils.showShort(message);
        progressBar.setVisibility(View.GONE);
        size=new AtomicInteger(0);
    }


    @OnClick({R.id.common_back_iv,R.id.btn_front,R.id.btn_next,R.id.iv1,R.id.iv2})
    public void onCLick(View view){
        switch (view.getId()){
            case R.id.common_back_iv:
            case R.id.btn_front:
                onBackPressed();
                break;
            case R.id.btn_next:
                if (!isNoNj&&(TextUtils.isEmpty(edYouLiang.getText().toString())||
                        TextUtils.isEmpty(edzhiliang.getText().toString()))){
                    ToastUtils.showShort("请填写完整信息");
                }else {
                    nongJiBean.setTrailerNum(edGuache.getText().toString());
                    nongJiBean.setAgentName(edJxs.getText().toString());
                    nongJiBean.setAgentArea(edJxsPlace.getText().toString());
                    nongJiBean.setDimensions(edSize.getText().toString());
                    nongJiBean.setLotId(edBianhao.getText().toString());
                    if (!TextUtils.isEmpty(edYouLiang.getText().toString())){
                        nongJiBean.setTankCapacity(Integer.parseInt(edYouLiang.getText().toString()));
                    }
                    if (!TextUtils.isEmpty(edzhiliang.getText().toString())){
                        nongJiBean.setMass(Integer.parseInt(edzhiliang.getText().toString()));
                    }
                    if (!TextUtils.isEmpty(edGonglv.getText().toString())){
                        nongJiBean.setPower(Integer.parseInt(edGonglv.getText().toString()));
                    }
                    nongJiBean.setLicenseNum(edCardNumber.getText().toString());
                    if (isNoNj){
                        if (paths.size()==0){
                            ToastUtils.showShort("请上传农机图片");
                            return;
                        }
                    }
                    progressBar.setVisibility(View.VISIBLE);
                    if (paths.size()>0){
                        for (int i=0;i<paths.size();i++){
                            presenter.upload(paths.get(i),i);
                        }
                    }else {

                        presenter.addDevice(nongJiBean,isNoNj);

                    }
                }

                break;
            case R.id.iv1:
                Matisse.from(DeviceAddStepTwoActivity.this)
                        .choose(MimeType.ofImage())
                        .capture(true)
                        .countable(true)
                        .maxSelectable(1)
                        .thumbnailScale(0.85f)
                        .captureStrategy(new CaptureStrategy(true, "com.beagle.njddapp"))
                        .imageEngine(GlideEngine.getInstance())
                        .showPreview(false) // Default is `true`
                        .forResult(CHOOSE_IMG_FRONT);
               
                break;
            case R.id.iv2:
                Matisse.from(DeviceAddStepTwoActivity.this)
                        .choose(MimeType.ofImage())
                        .capture(true)
                        .countable(true)
                        .maxSelectable(1)
                        .thumbnailScale(0.85f)
                        .captureStrategy(new CaptureStrategy(true, "com.beagle.njddapp"))
                        .imageEngine(GlideEngine.getInstance())
                        .showPreview(false) // Default is `true`
                        .forResult(CHOOSE_IMG_BACK);
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data==null){
            return;
        }
        if (requestCode==CHOOSE_IMG_FRONT){
            List<Uri> mSelected = Matisse.obtainResult(data);
            if (mSelected!=null&&mSelected.size()>0){
                String path=Utils.getPathFromUri(getApplicationContext(), mSelected.get(0));
                progressBar.setVisibility(View.VISIBLE);
                presenter.ocrXsz(path,"face");
            }
        }else if (requestCode==CHOOSE_IMG_BACK){
            List<Uri> mSelected = Matisse.obtainResult(data);
            if (mSelected!=null&&mSelected.size()>0){
                Glide.with(this).load(mSelected.get(0)).into(ivback);
                presenter.upload(Utils.getPathFromUri(getApplicationContext(),mSelected.get(0)),5);

            }
        }else if (requestCode==CHOOSE_IMG){
            List<Uri> mSelected = Matisse.obtainResult(data);
            if (mSelected!=null&&mSelected.size()>0){
                paths.add(Utils.getPathFromUri(getApplicationContext(),mSelected.get(0)));
                addIv(mSelected.get(0));
            }
        }
    }
    private void addIv(Uri uri) {
        if (paths.size()==3){
            lliv1.removeAllViews();
            imgViews.add(imgViews.size()-1,getImgView(uri));
            imgViews.remove(imgViews.size()-1);
            for (View view:imgViews){
                lliv1.addView(view);
            }
        }else {
            lliv1.removeAllViews();
            imgViews.add(imgViews.size()-1,getImgView(uri));
            for (View view:imgViews){
                lliv1.addView(view);
            }
        }
    }
    public View getImgView(Uri uri){
        View view=LayoutInflater.from(this).inflate(R.layout.item_add_img,null);
        view.setTag(uri);
        ImageView ivimg=view.findViewById(R.id.iv_img);
        Glide.with(this).load(uri).into(ivimg);
        ImageView ivcancle=view.findViewById(R.id.iv_cancle);
        ivcancle.setVisibility(View.VISIBLE);
        ImageView ivadd=view.findViewById(R.id.iv_add);
        ivadd.setVisibility(View.GONE);
        ivcancle.setOnClickListener(this);
        ivcancle.setTag(uri);
        return view;
    }

    @Override
    public void onClick(View view) {
        if (view.getId()==R.id.iv_cancle){
            Uri uri= (Uri) view.getTag();
            if (paths.size()==3){
                for (int i=0;i<lliv1.getChildCount();i++){
                    View child=lliv1.getChildAt(i);
                    if (child.getTag()!=null&&child.getTag() instanceof Uri){
                        Uri childUri= (Uri) child.getTag();
                        if (uri.equals(childUri)){
                            lliv1.removeView(child);
                            imgViews.remove(i);
                            paths.remove(i);
                            break;
                        }
                    }
                }
                addFirstIv();
            }else {
                for (int i=0;i<lliv1.getChildCount();i++){
                    View child=lliv1.getChildAt(i);
                    if (child.getTag()!=null&&child.getTag() instanceof Uri){
                        Uri childUri= (Uri) child.getTag();
                        if (uri.equals(childUri)){
                            lliv1.removeView(child);
                            imgViews.remove(i);
                            paths.remove(i);
                            break;
                        }
                    }
                }
            }
        }
    }
    @Override
    public void showZd(List<ZdBean> items) {

    }
    @Override
    public void uploadSuccess(UploadBean data,int index) {
        progressBar.setVisibility(View.GONE);
        if (index==4){
            nongJiBean.setFrontLicenseUrl(data.getVisitURL());
            Glide.with(this).load(data.getVisitURL()).into(ivFront);
        }else if (index==5){
            nongJiBean.setBackLicenseUrl(data.getVisitURL());
        }else {

            if (index==0){
                nongJiBean.setFrontPictureUrl(data.getVisitURL());
            }else if (index==1){
                nongJiBean.setSidePictureUrl(data.getVisitURL());
            }else if (index==2){
                nongJiBean.setBackPictureUrl(data.getVisitURL());
            }
            size.getAndIncrement();
            if (size.get()==paths.size()){
                presenter.addDevice(nongJiBean,isNoNj);
            }

        }
    }
    @Override
    public void addSuccess() {
        progressBar.setVisibility(View.GONE);
        ToastUtils.showLong("添加成功");
        tvTitle.postDelayed(new Runnable() {
            @Override
            public void run() {
                setResult(310);
                finish();
                EventBus.getDefault().post(new AddDeviceEvent());
            }
        },1000);

    }
}
